#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys
from PySide.QtCore import *
from PySide.QtGui import *
from PySide.QtWebKit import *
from PySide.QtMultimedia import *
from PySide.phonon import *

class Player(QObject):
	finished = Signal()
    	
	def __init__(self, parent = None):
		super(Player, self).__init__(parent)
		self.audioOutput = Phonon.AudioOutput(Phonon.MusicCategory, self)
		self.mediaObject = Phonon.MediaObject(self)
		self.mediaObject.finished.connect(self.finished)

		Phonon.createPath(self.mediaObject, self.audioOutput)

	@Slot()
	def play(self):
		self.mediaObject.play()

	def playFile(self, file):
		self.mediaObject.stop()
		self.mediaObject.clearQueue()
		self.mediaObject.setCurrentSource(file)
		self.mediaObject.play()

	@Slot()
	def pause(self):
		self.mediaObject.pause()

	def isPlaying(self):
		return self.mediaObject.state() == Phonon.PlayingState
	    
class WebView(QWebView):
	def __init__(self, parent = None):
		super(WebView, self).__init__(parent)		
		self.player = Player(self)
		self.player.setObjectName("player")
		self.player.finished.connect(self.onFinish)
		self.loadFinished.connect(self.onLoad)
		self.settings().setAttribute(QWebSettings.JavascriptEnabled, True)

	def dropEvent(self, event):
		if self.player.isPlaying():
			self.page().currentFrame().evaluateJavaScript("$(\"#playbutton\").click();")

		self.player.playFile(event.mimeData().urls()[0])
		self.page().currentFrame().evaluateJavaScript("$(\"#playbutton\").click();")

	@Slot(bool)
	def onLoad(self, ok):
		self.page().mainFrame().addToJavaScriptWindowObject("player", self.player)

	def onFinish(self):            
		self.page().currentFrame().evaluateJavaScript("$(\"#playbutton\").click();")
        
class MainWindow(QMainWindow):
        def __init__(self, parent = None):
                super(MainWindow, self).__init__(parent)
                self.webView = WebView(self)
                self.webView.load(QUrl('file:///' + QDir.currentPath() + '/ui/index.html'))
                self.webView.setContextMenuPolicy(Qt.NoContextMenu)
                self.setCentralWidget(self.webView)
                self.setFixedSize(640, 640)
                            
if __name__ == '__main__':
        # Create the Qt application
	app = QApplication(sys.argv)
	app.setApplicationName("funPlayer");

        # Create the MainWindow and show
	frame = MainWindow()
	frame.setWindowTitle("Fun Player written in PySide")
	frame.show()

	# Run the main Qt loop
	sys.exit(app.exec_())
